import React, {	Component } from 'react';
import { connect } from 'dva';
import { Table, Button, Row, Col, Form, Input, InputNumber, Popconfirm, Popover, Select, TreeSelect, Modal, Icon, DatePicker } from 'antd';
import ActivityListModal from './ActivityListModal';

const FormItem = Form.Item;
const Option = Select.Option;
const {	RangePicker } = DatePicker;

@window.regStateCache
class ActivityList extends Component {

	constructor() {
		super();
		this.state = {
      		modalVisible: false,
      		title: '',
    	};
	}

	handleSubmit(e, page, pageSize) {
		if(e) e.preventDefault();
		const {	activityPageSize } = this.props;
		this.props.form.validateFields((err, fieldsValue) => {
			if(err) return;
			if (fieldsValue.gmtCreate && fieldsValue.gmtCreate[0] && fieldsValue.gmtCreate[1]) {
	          fieldsValue.startGmtCreate = new Date(fieldsValue.gmtCreate[0]).format('yyyy-MM-dd');
	          fieldsValue.endGmtCreate = new Date(fieldsValue.gmtCreate[1]).format('yyyy-MM-dd');
	        }
	        delete fieldsValue.gmtCreate;
			this.props.dispatch({
				type: 'activity/queryActivityList',
				payload: { ...fieldsValue,
					pageIndex: typeof page === 'number' ? page : 1,
					pageSize: pageSize || activityPageSize,
				},
			});
		});
	}

	showModal() {
		const p = this;
	    this.setState({
	      modalVisible: true,
	      title: '新增',
	    });
	    this.props.dispatch({
	      type: 'sku/queryActivityItemList',
	      payload: {},
	    });
	}

	updateModal(id, e) {
    	if (e) e.stopPropagation();
		    const p = this;
		    p.setState({
		      modalVisible: true,
		      title: '修改',
		    }, () => {
		      p.props.dispatch({ type: 'activity/queryActivity', payload: { id } });
		      p.props.dispatch({ type: 'sku/queryActivityItemList', payload: {} });
	    });
    }

	handleDelete(id) {
	    const p = this;
	    this.props.dispatch({
	      type: 'activity/deleteActivity',
	      payload: { id },
	      cb() { p._refreshData(); },
	    });
	}

	closeModal() {
	    this.setState({ modalVisible: false }, () => {
	      this.props.dispatch({
	        type: 'activity/saveActivity',
	        payload: {},
	      });
	      this._refreshData();
	    });
	}

	render() {
		const p = this;
		const { form, dispatch, activityList = [], activityPage, activityPageSize, activityTotal, activityValues = {}} = this.props;
		const { title,modalVisible} = p.state;
		const {	getFieldDecorator,resetFields } = form;
		const formItemLayout = {
			labelCol: {	span: 10 },
			wrapperCol: { span: 14 },
		};
		const activityUrl = 'https://api.iruhua.com/api/static/activity/index.html?id=';
		const columnsList = [
			{	title: '活动编号',	dataIndex: 'activityNo', key: 'activityNo', width: 100 },
			{	title: '活动名称',
				dataIndex: 'activityName', 
				key: 'activityName', 
				width: 100,
				render(text,r) {
          			return <a href={`${activityUrl}${r.id}`} rel="noopener noreferrer" target="_blank">{text}</a>;
                },
			},
			{	title: '活动描述',	dataIndex: 'activityDesc',	key: 'activityDesc',	width: 100 },
			{	title: '活动主图',
			    dataIndex: 'activityMainPic', 
			    key: 'activityMainPic', 
			    width: 100,
			    render(text) {
                	if (!text) return '-';
          			const picList = JSON.parse(text).picList;
          			const t = picList.length ? picList[0].url : '';
          			return (
            			t ? <Popover title={null} content={<img src={t} style={{ width: 400 }} />}>
              			<img src={t} width={60} height={60} />
        				</Popover> : '-'
          			);
        		},
			},
			{	title: '活动开始时间',	dataIndex: 'activityStart', key: 'activityStart',	width: 100 },
			{	title: '活动结束时间',	dataIndex: 'activityEnd', key: 'activityEnd',	width: 100 },
			{	title: '活动创建时间',	dataIndex: 'gmtCreate', key: 'gmtCreate',	width: 100 },
			{	title: '创建者',	dataIndex: 'activityCreate', key: 'activityCreate',	width: 100 },
			{ 	title: '操作',
		        dataIndex: 'operator',
		        key: 'operator',
		        width: 150,
		        render(text, record) {
		          return (
		            <div>
		              <a href="javascript:void(0)" style={{ margin: '0 10px' }} onClick={p.updateModal.bind(p, record.id)}>修改</a>
		              <Popconfirm title="确定删除此商品活动？" onConfirm={p.handleDelete.bind(p, record.id)}>
		                <a href="javascript:void(0)" style={{ marginRight: 10 }}>删除</a>
		              </Popconfirm>
		            </div>);
		        },
		    },
		];

		const paginationProps = {
			total: activityTotal,
		    current: activityPage,
		    pageSize: activityPageSize,
		    showSizeChanger: true,
		    onChange(pageIndex) {
		       p.handleSubmit(null, pageIndex);
		    },
		    pageSizeOptions: ['20', '50', '100', '200', '500'],
		    onShowSizeChange(current, size) {
		       p.handleSubmit(null, 1, size);
		    },
		};

		return(
		<div>
        <div className="refresh-btn"><Button type="ghost" size="small" onClick={this._refreshData.bind(this)}>刷新</Button></div>
        <Form onSubmit={this.handleSubmit.bind(this)}>
          <Row gutter={20} style={{ width: 800 }}>
            <Col span="8">
              <FormItem
                label="活动编号"
                {...formItemLayout}
              >
                {getFieldDecorator('activityNo', {})(
                  <Input placeholder="请输入活动编号" />)}
              </FormItem>
            </Col>
            <Col span="8">
              <FormItem
                label="活动名称"
                {...formItemLayout}
              >
                {getFieldDecorator('activityName', {})(
                  <Input placeholder="请输入活动名称" />)}
              </FormItem>
            </Col>
            <Col span="8">
              <FormItem
                label="活动创建者"
                {...formItemLayout}
              >
                {getFieldDecorator('activityCreate', {})(
                  <Input placeholder="请输入创建者" />)}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={20} style={{ width: 800 }}>
          	<Col style={{ marginLeft: 6 }}>
              <FormItem
                label="创建时间范围"
                labelCol={{ span: 3 }}
              >
                {getFieldDecorator('gmtCreate')(<RangePicker />)}
              </FormItem>
            </Col>
          </Row>
          <Row style={{ marginLeft: 13 }}>
            <Col className="listBtnGroup">
              <Button htmlType="submit" size="large" type="primary">查询</Button>
              <Button size="large" type="ghost" onClick={() => { resetFields(); }}>清空</Button>
            </Col>
          </Row>
          <Row className="operBtn">
          	<Col>
          		<Button type="primary" size="large" onClick={p.showModal.bind(p)} style={{ float: 'left' }}>新增活动商品</Button>
          	</Col>	
          </Row>
        </Form>
        <Row>
          <Col>
            <Table
              columns={columnsList}
              dataSource={activityList}
              bordered
              rowKey={record => record.id}
              pagination={paginationProps}
              size="large"
              scroll={{ y: 640, x: 300 }} 
            />
          </Col>
         </Row>
         <ActivityListModal
          visible={modalVisible}
          close={this.closeModal.bind(this)}
          modalValues={activityValues}
          title={title}
          dispatch={dispatch}
        />
      </div>
		);
	}
}

function mapStateToProps(state) {
	const {activityList, activityPage, activityPageSize, activityTotal, activityValues} = state.activity;
	return { activityList, activityPage, activityPageSize, activityTotal, activityValues};
}

export default connect(mapStateToProps)(Form.create()(ActivityList));